/**
 *    https://gitee.com/gitsc/pro-cloud/
 *     @Author Aijm 2929793435@qq.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.cloud.auth.handler;

import com.cloud.auth.service.SysUserService;
import com.cloud.common.oauth.security.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;


/**
 * @Author Aijm
 * @Description 认证成功后的处理
 * @Date 2019/12/21
 */
@Slf4j
@Component
public class ProAuthenticationSuccessEventHandler implements ApplicationListener<AuthenticationSuccessEvent> {

	@Autowired
	private SysUserService sysUserService;

	/**
	 *  事件处理成功
	 * @param event
	 */
	@Override
	public void onApplicationEvent(AuthenticationSuccessEvent event) {
		//这里的事件源除了登录事件（UsernamePasswordAuthenticationToken）
		//还有可能是token验证事件源（OAuth2Authentication）
		if(event.getSource().getClass().getName().equals("org.springframework.security.authentication.UsernamePasswordAuthenticationToken")){
			return ;
		}

		Authentication authentication = event.getAuthentication();
		SecurityUser user = (SecurityUser)authentication.getPrincipal();

		// 登录成功后的操作
		sysUserService.updateByLogin(user.getUsername());
		log.info("登录成功! 用户：{} ", authentication.getPrincipal());
	}
}